package com.jboltai.capability.vdb;

import com.tencent.tcvectordb.exception.VectorDBException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 向量数据库操作结果
 */
public class VDBOptResult<T> {


    private static final Pattern TENCENT_EXCEPTION_MSG_PATTERN = Pattern.compile("message=([^,]*)|\"msg\":\"([^\"]*)\"");

    /**
     * 操作是否成功
     */
    private boolean success;

    /**
     * 错误信息
     */
    private String msg;

    /**
     * 操作结果
     */
    private T result;

    /**
     * 异常
     */
    private Throwable exception;

    public VDBOptResult(){}

    public VDBOptResult(boolean success, T result) {
        this.success = success;
        this.result = result;
    }

    public VDBOptResult(boolean success, T result, String msg) {
        this.success = success;
        this.msg = msg;
        this.result = result;
    }

    public VDBOptResult(Throwable exception) {
        this.success = false;
        this.setException(exception);
    }
    public VDBOptResult(String failMsg) {
        this.success = false;
        this.msg = failMsg;
    }

    public VDBOptResult(String msg, Throwable exception) {
        this.success = false;
        this.msg = msg;
        this.setException(exception);

    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    /**
     * 获取完整的错误信息
     * @return
     */
    public String getFullMsg() {
        StringBuilder full = new StringBuilder();
        if (full != null) {
            full.append("[message]:").append(this.msg).append("\n");
        }
        if (this.exception != null) {
            full.append("[exception]:").append(this.exception.getMessage());
        }
        return full.toString();
    }
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }

    public Throwable getException() {
        return exception;
    }

    public void setException(Throwable exception) {
        this.exception = exception;
        if (exception != null) {
            exception.printStackTrace();
        }
        if (this.msg == null && exception != null && exception instanceof VectorDBException) {
            Matcher matcher = TENCENT_EXCEPTION_MSG_PATTERN.matcher(exception.getMessage());
            if (matcher.find()) {
                String extractedMsg = matcher.group(1);
                this.msg = extractedMsg;
            }
        }
    }
}
